import { ApiTags } from '@nestjs/swagger'
import {
  Controller,
  Get,
  Post,
  Param,
  Response,
  Request,
  Body,
  UseGuards,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { UsersService } from './users.service'
import { User } from './users.entity'
import { AuthGuard } from '@nestjs/passport'
import { Express } from 'express'
import { diskStorage } from 'multer'
import { extname } from 'path'
import { CreateCatDto, CrateUserDto } from './usersDto'
@Controller('users')
export class UsersController {
  constructor(private readonly usersSrvice: UsersService) {}
  @ApiTags('获取手机验证码')
  @Get('getTelCode')
  getTelCode(@Response() res): string | any {
    //随机4位数字
    const code = Math.floor(Math.random() * 10000)
    console.log('code', code)
    res.cookie('name', 'zhangsan', { maxAge: 900000, httpOnly: true })
    return {
      msg: 200,
      code,
    }
  }
  @ApiTags('测试')
  @Get('index/:id')
  // @UseGuards(AuthGuard('jwt'))
  index(@Param() params, @Request() req): string | any {
    console.log(params.id)
    // const user = new User()
    // user.tel = '111111'
    // user.code = '12345'
    // const result = this.usersSrvice.created(user)

    // return result
  }
  @ApiTags('登录注册')
  @Post('register')
  register(@Body() userData: CrateUserDto) {
    return this.usersSrvice.created(userData)
  }

  @ApiTags('上传图片')
  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './upload',
        filename: (req, file, callback) => {
          const name = file.originalname.split('.')[0]
          const fileExtName = extname(file.originalname)
          const randomName = Array(4)
            .fill(null)
            .map(() => Math.round(Math.random() * 16).toString(16))
            .join('')
          callback(null, `${name}-${randomName}${fileExtName}`)
        },
      }),
      fileFilter: (req, file, callback) => {
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
          return callback(new Error('Only image files are allowed!'), false)
        }
        callback(null, true)
      },
    }),
  )
  uploadFile(
    @Body() createPersonDto: CreateCatDto,
    @UploadedFile() file: Express.Multer.File,
  ) {
    console.log('file', file)
    console.log(`received: ${JSON.stringify(createPersonDto)}`)
    return {
      createPersonDto,
      file,
    }
    // fs.writeFileSync(file.originalname, file.buffer)
  }
}
